package club.hicode.daydayup.netty.udp.client;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.core.thread.ThreadUtil;
import com.github.jsonzou.jmockdata.JMockData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.util.concurrent.TimeUnit;

/**
 * UDP的Server
 *
 * @author Liu Chunfu
 * @date 2018-07-09 上午11:19
 **/
public class UdpClient {

    public static Channel CHANNEL;

    public void run(int port) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            Channel channel = bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpChannelInitializer()).bind(0)
                    .sync().channel();
            CHANNEL = channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            try {
                new UdpClient().run(9876);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        ThreadUtil.sleep(1, TimeUnit.SECONDS);
        AbstractReq req = new AbstractReq();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {

                MessageBo mock = JMockData.mock(MessageBo.class);
                MessageBo req1 = req.req(mock);
                System.out.println("收到" + req1);
            }).start();

        }

    }
}
